package com.hxzy.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

/**
 *  功能拦截某些URL地址，要求 9：00-10：00才能访问，否则提示不允许访问
 *
 * @author tonneyyy
 */
public class BetweenTimeInterceptor  implements HandlerInterceptor{

    /**
     * 访问handler之前做的事情，return false，后面不用再执行了
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //当前请求访问地址
        String url=request.getRequestURI();
        if(url.equals("/demo01")){

            //时间点 9：00-10：00
            //当前时间
            int hour= LocalDateTime.now().getHour();
            if(hour>=9 && hour<=10){
                return true;
            }

            writeJson(response);

            return false;
        }else{
            //放行
            return true;
        }
    }


    private void writeJson(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print("当前时间不允许访问，开发时间点为 9：00-10：00");
        out.flush();
        out.close();
    }
}
